package com.wzm.moviepic.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.umeng.socialize.bean.LIKESTATUS;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.wzm.anmi.ViewExpandAnimation;
import com.wzm.bean.AdInfo;
import com.wzm.bean.DownInfo;
import com.wzm.bean.MovieInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.manager.ManagerTab;
import com.wzm.manager.Tag;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.moviepic.slidingmenu.Main1Activity;
import com.wzm.moviepic.weight.AdHeadViewPager;
import com.wzm.moviepic.weight.EmptyViewUtils;
import com.wzm.moviepic.weight.PullToRefreshView;
import com.wzm.moviepic.weight.PullToRefreshView.OnFooterRefreshListener;
import com.wzm.moviepic.weight.PullToRefreshView.OnHeaderRefreshListener;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;
import com.wzm.utils.UtilsTools;

@SuppressLint("ValidFragment")
public class MainFragment extends Fragment implements OnHeaderRefreshListener,OnFooterRefreshListener{
	private PullToRefreshView mPullToRefreshView = null;
	private ListView listView = null;
	private Page1Adapter pAdapter = null;
	
    private FinalBitmap fb = null;
    private FinalHttp fh = null;
    
    private View mEmptyLoadingView = null;
    private View mEmptyFailView = null;
    //电影列表
    private ArrayList<MovieInfo> mList = null;
    
    private Context mContext = null;
    
    private int currentItem = 0;
    private ScheduledExecutorService scheduledExecutorService;
    
    private ArrayList<AdInfo> adList = new ArrayList<AdInfo>();
    
    private int screen_width = 0;

    
    //广告VIEW
    private View adHeader = null;
    private AdHeadViewPager adHeaderPager = null;
    private AdAdapter adAdapter = null;
    
    private ManagerTab mTab = null;
    private int oldPos = 0;
    public MainFragment()
    {
    	
    }
	public MainFragment(ManagerTab mt)
    {
		mTab = mt;
    }
    
    
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mContext = getActivity();
		//获取电影列表
		mList = AppManager.getInstance(mContext).getmList();
		
		View view = inflater.inflate(R.layout.fragment_main_new, null);
		mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.main_pull_refresh_view);
		listView = (ListView)view.findViewById(R.id.movieslist);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
        mList.clear();

		//注册更新广播
		IntentFilter intentFilter = new IntentFilter(Tag.UPDATELIST);
		getActivity().registerReceiver( uiupdateReceiver , intentFilter); 
		intentFilter = null;
        
        
		if(mTab != null)
		{
			
			listView.setOnScrollListener(new OnScrollListener() {
				
				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					//Logger.info(firstVisibleItem+"xxVSoo"+oldPos);
					if(firstVisibleItem>oldPos)
					{
						mTab.hidetab();
						oldPos = firstVisibleItem;
					}else if(firstVisibleItem<oldPos){
						mTab.showtab();
						oldPos = firstVisibleItem;
					}
				}
			});
		}
		
		
		
		
        
        //初始化HTTP，网络图片组件
        fh = AppManager.getInstance(getActivity()).getFh();		
		fb = FinalBitmap.create(getActivity(),Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);
		fb.configLoadingImage(R.drawable.spic);
		fb.configLoadfailImage(R.drawable.spic);
        
		//添加头部广告
		adHeader = LayoutInflater.from(mContext).inflate(R.layout.ad_headerview, null);
		addHead();
		//获取广告数据
		getAdList();
		
		
		//设置电影列表适配器
		pAdapter = new Page1Adapter(getActivity(),mList);
		listView.setAdapter(pAdapter);
        
		//获取电影
		getMovieList();	
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				// TODO Auto-generated method stub
				View footer = v.findViewById(R.id.introlayout);
				ViewExpandAnimation vani = new ViewExpandAnimation(footer);
				footer.startAnimation(vani);
				vani = null;	
			}			
		});
		
		return view;
	}
	
	
	//广告头初始化
	private void addHead(){
		listView.addHeaderView(adHeader);
		adHeaderPager = (AdHeadViewPager)adHeader.findViewById(R.id.vp_ad_head);
		
		DisplayMetrics dm = new DisplayMetrics();  
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);  
        screen_width = dm.widthPixels;  

		//动态改变图片大小
		LinearLayout.LayoutParams laParams=(LinearLayout.LayoutParams)adHeaderPager.getLayoutParams();
		laParams.height=460*screen_width/640;
	    laParams.width=screen_width;
	    adHeaderPager.setLayoutParams(laParams);
		
	    adAdapter = new AdAdapter();
	    adHeaderPager.setAdapter(adAdapter);
	}
	
	

	public void onLoadOver()
	{
		mPullToRefreshView.onFooterRefreshComplete();
		mPullToRefreshView.onHeaderRefreshComplete("最后更新:"+UtilsTools.getTagString(getActivity(), Tag.DATE));
	}
	
	//底部刷新
	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		// TODO Auto-generated method stub
		if(AppApplication.mNetWorkState!=0)
		{
			getNextPage();
		}else{
			Toast.makeText(getActivity(), "没网你怎么看更多...", Toast.LENGTH_SHORT).show();
			onLoadOver();
		}	
		
		//mPullToRefreshView.onFooterRefreshComplete();
	}
	//头部刷新
	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		// TODO Auto-generated method stub
		if(AppApplication.mNetWorkState!=0)
		{
			getMovieList();
			getAdList();
		}else{
			Toast.makeText(getActivity(), "没网你怎么刷新...", Toast.LENGTH_SHORT).show();
			onLoadOver();
		}
		
		//mPullToRefreshView.onHeaderRefreshComplete();
	}
	
	public void getNextPage()
	{
		if(null!=mList&&mList.size()>0)
		{
			final String baseid = String.valueOf(mList.get(mList.size()-1).getId());
			//Logger.error(mList.get(mList.size()-1).getId());
			
			String cacheMovielist = ConfigCache.getUrlCache(AppConfig.MOVIE_URL+baseid);
			if(cacheMovielist==null)
	        {
				AjaxParams params = new AjaxParams();
				
				params.put("baseid",baseid);
				params.put("order", "1");
				params.put("ver", Tag.VerNum);
				params.put("online_time", mList.get(mList.size()-1).getOnline_time());
				fh.post(AppConfig.MOVIE_URL,params, new AjaxCallBack<Object>() {

					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						super.onSuccess(t);
						
						ConfigCache.setUrlCache((String)t, AppConfig.MOVIE_URL+baseid);	
						String json = t.toString();											
						excuteJson(json,false);
						onLoadOver();
					}

					@Override
					public void onFailure(Throwable t, String strMsg) {
						// TODO Auto-generated method stub
						super.onFailure(t, strMsg);
						onLoadOver();
					}
					
				});
	        }else{
	        	excuteJson(cacheMovielist,false);
	        	onLoadOver();
	        }
			
		}else{
			onLoadOver();
		}		
	}
	
	
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		mContext.unregisterReceiver(uiupdateReceiver);
		super.onDestroy();
	}

	//获取电影列表
	public void getMovieList()
	{
		final String baseid="-1";
		//先进行缓存获取
        String cacheMovielist = ConfigCache.getUrlCache(AppConfig.MOVIE_URL+baseid);
        if(cacheMovielist==null)
        {
        	//请求数据
        	
        	AjaxParams params = new AjaxParams();
    		params.put("baseid",baseid);
    		params.put("order", "0");//最新
    		params.put("ver", Tag.VerNum);
        	//不传参数默认获取20条
    		fh.post(AppConfig.MOVIE_URL,params,new AjaxCallBack<Object>() {

				@Override
				public void onStart() {
					showLoadingEmptyView();
				}

				@Override
				public void onLoading(long count, long current) {
					
				}

				@Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub

					//更新成功
					UtilsTools.setTagString(getActivity(), Tag.DATE, UtilsTools.getDate());	
					
					ConfigCache.setUrlCache((String)t, AppConfig.MOVIE_URL+baseid);					
					excuteJson(t.toString(),true);
					onLoadOver();
					
					
				}

				@Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					//Logger.error("onFailure"+strMsg);
					//listView.setAdapter(null);
					showFailEmptyView();
					onLoadOver();
					//super.onFailure(t, strMsg);
				}
    			
			});
    		
    		
    		params = null;
        }else{
        	excuteJson(cacheMovielist,true);
        	onLoadOver();
        }

	}
	
	//show loading view when init and loading data from network
    protected void showLoadingEmptyView() {
        if (mEmptyFailView == null) {
            mEmptyLoadingView = EmptyViewUtils.createLoadingView(getActivity());
        }
        ((ViewGroup)listView.getParent()).removeView(mEmptyFailView);
        ((ViewGroup)listView.getParent()).addView(mEmptyLoadingView);
        //listView.removeAllViews();
        listView.setEmptyView(mEmptyLoadingView);
    }

    //show fail view when loading data fail
    protected void showFailEmptyView() {
        if (mEmptyFailView == null) {
            mEmptyFailView = EmptyViewUtils.createFailView(getActivity());
        }
        ((ViewGroup)listView.getParent()).removeView(mEmptyLoadingView);
        ((ViewGroup)listView.getParent()).addView(mEmptyFailView);
        //listView.removeAllViews();
        listView.setEmptyView(mEmptyFailView);
        
        
        mEmptyFailView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getMovieList();
				getAdList();
			}
		});
        
    }
    
	public void excuteJson(String json,boolean isclear)
	{
		
		try {
			JSONObject result = new JSONObject(json);
			int status = result.getInt("status");
			if(status==1)
			{
				
				if(isclear)
				{
					mList.clear();
				}			
				JSONArray list = result.getJSONArray("movies");
				if(list.length()==0)
				{
					Toast.makeText(getActivity(), "别刷了,没有数据了哦", Toast.LENGTH_SHORT).show();
					return;
				}
				
				for(int i=0;i<list.length();i++)
				{
					MovieInfo mi = new MovieInfo();
					
					JSONObject obj = list.getJSONObject(i);
					//电影id
					mi.setId(obj.getString("id"));
					//电影名字
					mi.setName(obj.getString("name"));
										
					//电影作者
					mi.setAuthor(obj.getString("author"));
					//电影导演
					mi.setActor(obj.getString("actor"));
					//电影介绍
					mi.setIntro(obj.getString("intro"));
					//电影大图
					mi.setBpic(obj.getString("bpic"));
					//电影小图
					mi.setSpic(obj.getString("spic"));
					//标签
					mi.setTag(obj.getString("tags"));
					//类型
					mi.setZoneid(obj.getString("zoneid"));
					//评分
					mi.setScore(obj.getString("score"));
					//上映时间
					mi.setShowtime(obj.getString("showtime"));
					//即将上映
					mi.setComing(obj.getString("coming"));
					//上映时间
					mi.setComing_time(obj.getString("coming_time"));
					//副标题
					mi.setSub_title(obj.getString("sub_title"));
					//推荐
					mi.setJian(obj.getString("jian"));
					//顶
					mi.setDing(obj.getString("ding"));
					//踩
					mi.setCai(obj.getString("cai"));
					//浏览次数
					mi.setPlayed(obj.getString("played"));
					//服务器上线时间，判断是否要显示新
					mi.setOnline_time(obj.getString("online_time"));
					//热门
					mi.setHot(obj.getString("hot"));
					mList.add(mi);
					mi = null;					
				}
				
				pAdapter.notifyDataSetChanged();
				
				
				
				Logger.info("电影数据请求完毕："+mList.size());
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Logger.error(e.getMessage());
			//listView.setAdapter(null);
			//showFailEmptyView();
			//e.printStackTrace();						
		}
	}
	
	
	
	
	
	
	
	
	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		//Logger.info("MainFragment onResume");
		if(null!=pAdapter)
		{
			
			pAdapter.notifyDataSetChanged();
		}
		super.onResume();
	}










	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			setAd();
		};
	};
    
	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (adList) {
				if(adList.size()>1)
				{
					handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
				}				
			}
		}

	}
	
	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 3, 5, TimeUnit.SECONDS);
		
		super.onStart();
	}
    
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		//关闭广告滚动定时器
		scheduledExecutorService.shutdown();
		super.onStop();
	}
	
	public void setAd()
	{
		currentItem = (currentItem + 1) % adList.size();
		adHeaderPager.setCurrentItem(currentItem);
	}
	
	//获取广告列表
	public void getAdList()
	{
		//Logger.info("getAdList");
		//WIFI,4个小时，MOBILE 6个小时
		String AdCachelist = ConfigCache.getUrlCache(AppConfig.ADURL);
		if(AdCachelist==null)
		{//重新获取
			//Logger.info("111111111");
			AjaxParams params = new AjaxParams();
    		params.put("platform","Android");
    		fh.post(AppConfig.ADURL, params,new AjaxCallBack<Object>() {

				@Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub
					super.onSuccess(t);
					String json = t.toString();
					//Logger.info("ad:"+json);
					ConfigCache.setUrlCache(json, AppConfig.ADURL);	
					excuteAdJson(json);
				}

				@Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					super.onFailure(t, strMsg);
					//Logger.error("aderror:"+strMsg);
				}
    			
			});
    		params = null;
		}else{
			//Logger.info("222222222");
			excuteAdJson(AdCachelist);
		}
	}
	
	public void excuteAdJson(String json)
	{
		
		try {
			JSONObject obj = new JSONObject(json);
			int status = obj.getInt("status");
			if(status==1)
			{
				adList.clear();
				JSONArray alist = obj.getJSONArray("top");
				if(alist.length()<1)
				{
					return;
				}
				for(int i=0;i<alist.length();i++)
				{
					JSONObject item = alist.getJSONObject(i);
					AdInfo adinfo = new AdInfo();
					adinfo.setId(item.getString("id"));
					adinfo.setImage(item.getString("image"));
					adinfo.setApp_type(item.getString("app_type"));
					adinfo.setName(item.getString("name"));
					adinfo.setCompany(item.getString("company"));
					adinfo.setIcon(item.getString("icon"));
					adinfo.setScore(item.getString("score"));
					adinfo.setIntro(item.getString("intro"));
					adinfo.setTop_img(item.getString("top_img"));
					adinfo.setCell_img(item.getString("cell_img"));
					List<String> mlist = new ArrayList<String>();
					JSONArray slist = item.getJSONArray("screenshots");
				    
					for(int ii=0;ii<slist.length();ii++)
					{
						String sitem = slist.getString(ii);
						//Logger.info(sitem);
						mlist.add(sitem);
					}
					adinfo.setMlist(mlist);
					mlist = null;
					adinfo.setOpen_url(item.getString("open_url"));
					adinfo.setOpen_url_title(item.getString("open_url_title"));
					adinfo.setWebsite(item.getString("website"));
					adinfo.setEmail(item.getString("email"));
					adinfo.setShow_details(item.getString("show_details"));
					ArrayList<PicInfo> advpics = new ArrayList<PicInfo>();
					JSONArray advlist = item.getJSONArray("adv_pics");
					for(int j=0;j<advlist.length();j++)
					{
						JSONObject picinfoitem = advlist.getJSONObject(j);
						PicInfo pi = new PicInfo();
						pi.setId(picinfoitem.getString("id"));
						pi.setpIndex(picinfoitem.getString("index"));
						pi.setImage(picinfoitem.getString("image"));
						pi.setIntro(picinfoitem.getString("intro"));
						pi.setScript(picinfoitem.getString("script"));
						advpics.add(pi);
						pi = null;
					}
					advpics.add(null);
					adinfo.setAdvpic(advpics);
					advpics = null;
					adList.add(adinfo);						
					adinfo = null;
				}
				
				Logger.info("广告请求完毕："+adList.size());
				adAdapter.notifyDataSetChanged();
				
				
				ArrayList<AdInfo> adbList =new ArrayList<AdInfo>();
				//添加片尾广告
				JSONArray blist = obj.getJSONArray("read");
				for(int i=0;i<blist.length();i++)
				{
					JSONObject item = blist.getJSONObject(i);
					AdInfo adinfo = new AdInfo();
					adinfo.setId(item.getString("id"));
					adinfo.setImage(item.getString("image"));
					adinfo.setApp_type(item.getString("app_type"));
					adinfo.setName(item.getString("name"));
					adinfo.setCompany(item.getString("company"));
					adinfo.setIcon(item.getString("icon"));
					adinfo.setScore(item.getString("score"));
					adinfo.setIntro(item.getString("intro"));
					adinfo.setTop_img(item.getString("top_img"));
					adinfo.setCell_img(item.getString("cell_img"));
					List<String> mlist = new ArrayList<String>();
					JSONArray slist = item.getJSONArray("screenshots");
				    
					for(int ii=0;ii<slist.length();ii++)
					{
						String sitem = slist.getString(ii);
						//Logger.info(sitem);
						mlist.add(sitem);
					}
					adinfo.setMlist(mlist);
					mlist = null;
					adinfo.setOpen_url(item.getString("open_url"));
					adinfo.setOpen_url_title(item.getString("open_url_title"));
					adinfo.setWebsite(item.getString("website"));
					adinfo.setEmail(item.getString("email"));
					adinfo.setShow_details(item.getString("show_details"));
					ArrayList<PicInfo> advpics = new ArrayList<PicInfo>();
					JSONArray advlist = item.getJSONArray("adv_pics");
					for(int j=0;j<advlist.length();j++)
					{
						JSONObject picinfoitem = advlist.getJSONObject(i);
						PicInfo pi = new PicInfo();
						pi.setId(picinfoitem.getString("id"));
						pi.setpIndex(picinfoitem.getString("index"));
						pi.setImage(picinfoitem.getString("image"));
						pi.setIntro(picinfoitem.getString("intro"));
						pi.setScript(picinfoitem.getString("script"));
						advpics.add(pi);
						pi = null;
					}
					adinfo.setAdvpic(advpics);
					advpics = null;
					adbList.add(adinfo);	
					adinfo = null;
				}
				AppApplication.getInstance().setAdbList(adbList);				
				adbList = null;
			}			
			obj = null;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			Logger.error("adjsonerror:"+e.getMessage());
		}
	}
	
	
	
 	/**
	 * 填充广告模块ViewPager页面的适配器
	 */
	private class AdAdapter extends PagerAdapter {
		private LayoutInflater  mInflater;
		
		AdAdapter()
		{
			mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);	
		}
		@Override
		public int getCount() {
			return adList.size();
		}
		

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			// TODO Auto-generated method stub
			
			if(position>adList.size()-1)
			{
				return null;
			}			
			final AdInfo adinfo = adList.get(position);
			
			View view = mInflater.inflate(R.layout.ad_item, container, false);   
			
			((ViewPager)container).addView(view);
			ImageView adImage = (ImageView)view.findViewById(R.id.ad_img);
			adImage.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String showDetail = adinfo.getShow_details();
					if(showDetail.equals("0"))
					{//打开链接
						Uri uri = Uri.parse(adinfo.getOpen_url());  
						Intent it = new Intent(Intent.ACTION_VIEW, uri);  
						startActivity(it);
						getActivity().overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
						it = null;
						
					}else if(showDetail.equals("1"))
					{//打开详细页面
						Intent it = new Intent(mContext,AdIntroActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("adinfo", adinfo);
						it.putExtras(bundle);
						startActivity(it);
						getActivity().overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
						it = null;
					}
				}
			});
			//Logger.error("photo:"+adinfo.getTop_img());
			fb.display(adImage, adinfo.getTop_img(),640,460);				
			TextView tv_title = (TextView)view.findViewById(R.id.ad_title);
			tv_title.setText(adinfo.getName());
			return view;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager)arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}

		
	//电影列表适配器
	public class Page1Adapter extends BaseAdapter {
		
		private ArrayList<MovieInfo> mList = null;
		private Context mContext = null;
		private LayoutInflater  mInflater;
		private FinalBitmap fb = null;
		//private Animation zoomin;
		
		private int mLcdWidth = 0;
		private float mDensity = 0;
		
		Page1Adapter(Context context,ArrayList<MovieInfo> list)
		{
			
			mContext = context;
			mList = list;
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);		
			//zoomin = AnimationUtils.loadAnimation(mContext,R.anim.zoomin);				
			fb = FinalBitmap.create(mContext,Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);
			//fb = FinalBitmap.create(mContext);
			fb.configLoadingImage(R.drawable.spic);
			fb.configLoadfailImage(R.drawable.spic);				
			getSystemInfo();
		}
		
		private void getSystemInfo(){
			DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
			mLcdWidth = dm.widthPixels;
			mDensity = dm.density;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			
			final int pos = position; 
			
				View view = convertView;
				ViewHolder viewHolder = null;
				if(view == null)
				{
					view = mInflater.inflate(R.layout.cell_movie_item, parent, false);   
					viewHolder = new ViewHolder();
					viewHolder.movie_pic = (ImageView)view.findViewById(R.id.movie_pic);
					viewHolder.movie_name = (TextView)view.findViewById(R.id.movie_name);
					viewHolder.movie_type = (TextView)view.findViewById(R.id.movie_type);
					viewHolder.mLayout = (LinearLayout)view.findViewById(R.id.introlayout);
					viewHolder.movie_intro = (TextView)view.findViewById(R.id.movie_tvintro);
					viewHolder.btn_down = (LinearLayout)view.findViewById(R.id.lly_down);
					viewHolder.btn_read = (LinearLayout)view.findViewById(R.id.lly_read);
					viewHolder.btn_info = (LinearLayout)view.findViewById(R.id.lly_info);
					
					viewHolder.moive_author = (TextView)view.findViewById(R.id.movie_author);
					viewHolder.movie_time = (TextView)view.findViewById(R.id.movie_addtime);
					viewHolder.movie_ratebar = (RatingBar)view.findViewById(R.id.ratingBar);
					viewHolder.movie_tvrate = (TextView)view.findViewById(R.id.movie_rate);
					viewHolder.tv_cellread = (TextView)view.findViewById(R.id.tv_cellread);
					viewHolder.tv_downbtn = (TextView)view.findViewById(R.id.tv_downbtn);
					viewHolder.tv_played = (TextView)view.findViewById(R.id.tv_played);
					viewHolder.tv_ding = (TextView)view.findViewById(R.id.tv_ding);
					viewHolder.tv_cai = (TextView)view.findViewById(R.id.tv_cai);
					viewHolder.tv_subtitle = (TextView)view.findViewById(R.id.tv_subtitle);
					viewHolder.tag_left = (ImageView)view.findViewById(R.id.tag_left);
					viewHolder.tag_right = (ImageView)view.findViewById(R.id.tag_right);					
					viewHolder.tv_comingtime = (TextView)view.findViewById(R.id.tv_comingtime);
					viewHolder.iv_iunlike = (ImageView)view.findViewById(R.id.iv_iunlike);
					
					view.setTag(viewHolder);
				}else{
					viewHolder = (ViewHolder) view.getTag();
				}
				
			
				//
				final MovieInfo mi = mList.get(position);								
				viewHolder.movie_name.setText(mi.getName());
				viewHolder.movie_intro.setText(mi.getIntro());
				viewHolder.moive_author.setText(mi.getAuthor());
				viewHolder.movie_time.setText(mi.getShowtime());
				viewHolder.movie_ratebar.setRating(Float.parseFloat(mi.getScore()));
				viewHolder.movie_tvrate.setText(mi.getScore());
				viewHolder.movie_type.setText(mi.getTag());	
				
				
				//顶，踩，播放
				viewHolder.tv_played.setText(mi.getPlayed());
				//viewHolder.tv_ding.setText(mi.getDing());
				viewHolder.tv_cai.setText(mi.getCai());
				
				final TextViewPair TvPair = new TextViewPair(viewHolder.tv_ding);
				final UMSocialService controller = initAcitonBar(mContext, TvPair, mi);
				
				if(controller.getEntity().getLikeStatus()==LIKESTATUS.LIKE)
				{
					viewHolder.iv_iunlike.setImageResource(R.drawable.ilike);
				}else{
					viewHolder.iv_iunlike.setImageResource(R.drawable.iunlike);
				}
				
				
				if(!mi.getSub_title().equals("null")&&mi.getSub_title().length()>0)
				{
					viewHolder.tv_subtitle.setText(mi.getSub_title());
				}else{
					viewHolder.tv_subtitle.setText("");
				}
				
				//动态改变图片控件大小
				RelativeLayout.LayoutParams laParams=(RelativeLayout.LayoutParams)viewHolder.movie_pic.getLayoutParams();
				laParams.height=230*screen_width/640;
			    laParams.width=screen_width;
			    viewHolder.movie_pic.setLayoutParams(laParams);
			
			
				fb.display(viewHolder.movie_pic,mi.getSpic(),640,230);
				
				//阅读按钮
				viewHolder.btn_read.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(mi.getComing().equals("1"))
						{
							Toast.makeText(mContext, mi.getComing_time()+"上线,敬请期待哦", Toast.LENGTH_SHORT).show();
						}else{
							Intent intent = new Intent(mContext,ViewPagerActivity.class);			
							Bundle bundle = new Bundle();
							bundle.putSerializable("movieinfo", mi);
							intent.putExtras(bundle);
							mContext.startActivity(intent);
							intent = null;
						}
						
					}
				});
				//详细介绍按钮
				viewHolder.btn_info.setOnClickListener(new OnClickListener() {			
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent introintent = new Intent(mContext,MovieIntroActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("movieinfo", mi);
						bundle.putInt("pos", pos);
						introintent.putExtras(bundle);
						mContext.startActivity(introintent);
						getActivity().overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
						bundle = null;
						introintent = null;
					}
				});
			
			
				//下载按钮
				viewHolder.btn_down.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub		
						if(mi.getComing().equals("1"))
						{
							Toast.makeText(mContext, mi.getComing_time()+"上线,敬请期待哦", Toast.LENGTH_SHORT).show();
						}else{
							((Main1Activity)mContext).showleft();
							//把下载信息加入下载数据库
							DownInfo di = new DownInfo();
							di.setMovieid(mi.getId());
							di.setMoviename(mi.getName());
							di.setCurpage(0);
							di.setSize(0);
							Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from downinfo where movieid = ?", new String[]{mi.getId()});
							
							if(null!=cursor&&cursor.getCount()>0)
							{
								Toast.makeText(mContext, "已在下载队列中,可边下边看哦^_^", Toast.LENGTH_SHORT).show();
							}else{
								long downid = DBHelper.getInstance(mContext).insertDownInfo(di);
								Toast.makeText(mContext, "已加入下载队列", Toast.LENGTH_SHORT).show();
								//加入到下载队列
								AppApplication.getInstance().getDMap().put(di.getMovieid(), di);
								//更新UI
								Intent intent = new Intent(Tag.UPDATEUI);
						        mContext.sendBroadcast(intent);
						        
						        if(AppApplication.mNetWorkState!=NetworkUtils.NETWORN_NONE)
						        {					        	
						        	//启动下载服务
							        Intent service = new Intent(Tag.START);
									service.putExtra("action", Tag.DownPicList);
									service.putExtra("movieid", mi.getId());
								    mContext.startService(service);
								    intent = null;
						        }else{
						        	Toast.makeText(mContext, "网络检测失败，请检查网络", Toast.LENGTH_SHORT).show();
						        }    
							}
							
							if(null!=cursor)
							{
								cursor.close();
								di = null;
							}
						}
					}
				});
			
			
			
				//判断是否显示离线标签
				if(AppApplication.getInstance().getfMap().containsKey(mi.getId()))
				{
					viewHolder.tag_right.setVisibility(View.VISIBLE);
					viewHolder.tag_right.setImageResource(R.drawable.moviecell_download);
					viewHolder.tv_cellread.setText("离线阅读");
					viewHolder.tv_downbtn.setText("下载完成");
				}else{
					viewHolder.tv_downbtn.setText("离线下载");
					if(AppApplication.getInstance().getDMap().containsKey(mi.getId()))
					{
						viewHolder.tag_right.setVisibility(View.VISIBLE);
						viewHolder.tag_right.setImageResource(R.drawable.moviecell_downloading);
					}else{
						viewHolder.tag_right.setVisibility(View.INVISIBLE);
					}
					viewHolder.tv_cellread.setText("在线阅读");
				}
			
				//7天内都是新
//				Logger.info(UtilsTools.getNow()/1000L+"vs"+Long.valueOf(mi.getOnline_time()));
//				Logger.info(((UtilsTools.getNow()/1000L)-Long.valueOf(mi.getOnline_time()) +","+60*60*24*7));
//				Logger.info(((UtilsTools.getNow()/1000L)-Long.valueOf(mi.getOnline_time())-60*60*24*7));

				
				//标签期待
				if(mi.getComing().equals("1"))
				{
					viewHolder.tag_left.setVisibility(View.VISIBLE);
					viewHolder.tag_left.setBackgroundResource(R.drawable.moviecell_await);
					
					viewHolder.tv_comingtime.setText(mi.getComing_time());
					viewHolder.tv_comingtime.setVisibility(View.VISIBLE);
					
				}else{
					viewHolder.tv_comingtime.setVisibility(View.GONE);
					if(((UtilsTools.getNow()/1000L)-Long.valueOf(mi.getOnline_time())<60*60*24*7))
					{//7天
						viewHolder.tag_left.setVisibility(View.VISIBLE);
						viewHolder.tag_left.setBackgroundResource(R.drawable.moviecell_new);
					}else{
						//标签热门
						if(mi.getJian().equals("1"))
						{
							viewHolder.tag_left.setVisibility(View.VISIBLE);
							viewHolder.tag_left.setBackgroundResource(R.drawable.moviecell_jian);
						}else{
							//标签推荐
							if(mi.getHot().equals("1"))
							{
								viewHolder.tag_left.setVisibility(View.VISIBLE);
								viewHolder.tag_left.setBackgroundResource(R.drawable.moviecell_hot);
							}else{
								viewHolder.tag_left.setVisibility(View.GONE);
							}
						}					
					}	
				}
				
				
				
				// get footer height
				LinearLayout footer = viewHolder.mLayout;
				int widthSpec = MeasureSpec.makeMeasureSpec((int) (mLcdWidth - 10 * mDensity), MeasureSpec.EXACTLY);
				footer.measure(widthSpec, 0);
				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) footer.getLayoutParams();
				params.bottomMargin = -footer.getMeasuredHeight();
				footer.setVisibility(View.GONE); 				
				return view;
			} 
		}
		private class ViewHolder {
	        public ImageView movie_pic;
	        public TextView  movie_name;
	        public TextView  movie_type;
	        public TextView movie_intro;
	        public LinearLayout mLayout;
	        
	        public LinearLayout btn_read;
	        public LinearLayout btn_down;
	        public LinearLayout btn_info;
	        public LinearLayout lly_ad;
	        
	        public TextView moive_author;
	        public TextView movie_time;
	        
	        public RatingBar movie_ratebar;
	        public TextView movie_tvrate;
	        
//	        public ImageView movie_offline;
//	        public ImageView movie_downing;
	        
	        public TextView tv_cellread;
	        public TextView tv_downbtn;
	        
	        //1.0.4
	        public TextView tv_subtitle;
	        public TextView tv_played;
	        public TextView tv_ding;
	        public TextView tv_cai;
	        public TextView tv_comingtime;	        
	        public ImageView tag_left;
	        public ImageView tag_right;	        
	        public ImageView iv_iunlike;	        
	    };
	    
		private BroadcastReceiver uiupdateReceiver = new BroadcastReceiver() 
		{
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
			if(intent.getAction().equals(Tag.UPDATELIST))
			{
				pAdapter.notifyDataSetChanged();
				
				Logger.error("更新列表...........");
			}
		}
	};
	
	
	
	
	protected static UMSocialService initAcitonBar(Context context, TextViewPair tvPair, MovieInfo mi) {
		final TextViewPair mPair = tvPair;
		UMSocialService controller = UMServiceFactory.getUMSocialService(mi.getId(),
				RequestType.SOCIAL);

		if (!controller.getEntity().initialized) {
			//controller.setShareContent(tv.des);
			controller.initEntity(context, new SocializeClientListener() {
				@Override
				public void onStart() {
					
				}

				@Override
				public void onComplete(int status, SocializeEntity entity) {
					matchEntity(mPair, entity);
				}

			});
		} else {
			matchEntity(mPair, controller.getEntity());
		}
		return controller;
	}
	
	private synchronized static void matchEntity(final TextViewPair mPair, SocializeEntity entity) {
		if (entity != null) {
			mPair.likeTv.setText("" + entity.getLikeCount());
//			mPair.commentBt.setText("评论:  " + entity.getCommentCount());
//			mPair.shareBt.setText("分享:  " + entity.getShareCount());
		}
	}
	
	
	private static class TextViewPair {
		TextView likeTv;

		public TextViewPair(TextView likeTv) {
			super();
			this.likeTv = likeTv;			
		}
	}
	    
	
}
